<template>
  <div v-loading="loading" class="app-container">
    <div class="filter-container">

      <!-- 头部导航搜索添加等 -->

      <!-- <el-input v-model="listQuery.title" placeholder="输入关键词" style="width: 200px;" class="filter-item"
        @input="handleFilter()" @keyup.enter.native="handleFilter" /> -->

      <el-select
        filterable
        v-if='register_list'
        v-model="listQuery.register_id"
        style="width: 140px; margin-left: 10px;"
        class="filter-item"
        @change="handleFilter">
        <el-option
          v-for="item in register_list"
          :key="item.id"
          :label="item.name"
          :value="item.id" />
      </el-select>


      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-download"
        @click="handleDownload">
        导出全部
      </el-button>
    </div>

    <!-- 列表主体 -->
    <el-table
     @selection-change="handleSelectionChange"
    :data="tableData"
    border fit highlight-current-row
    style="width: 100%;"
    @sort-change="sortChange">
      <!--  -->
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>


      <el-table-column label="ID" fixed prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="基本信息" fixed align="left">
        <template slot-scope="{row}">
          <h2>礼物名：{{ row.name }}</h2>
          <p>订单号：{{ row.order_code }}</p>
          <p>赠送对象：{{ row.register.name }}</p>
          <p>单价：{{ row.money }}</p>
          <p>数量：{{ row.number }}</p>
          <p>总计：{{ row.money_all }}</p>
          <p>赠送时间：{{ row.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</p>

        </template>
      </el-table-column>





      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <div style="margin-bottom: 10px;">


          </div>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total>0" :page-sizes="pagesizes" :total="total" :page.sync="listQuery.page"
      :limit.sync="listQuery.limit" @pagination="list" />

    <!-- 添加修改 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="top" label-width="70px"
        style="width: 400px; margin-left:50px;">

        <el-form-item label="参赛姓名" prop="name">
          <el-input v-model="temp.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="分组" prop="name">
          <el-select
            v-if='fenzu2'
            v-model="temp.fenzu_info_id"
          >
            <el-option
              v-for="item in fenzu2"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item
        label="微信姓名"
        prop="name"
        v-if = 'dialogStatus=="create"||temp.is_system==1'>
          <el-input v-model="temp.wx_name" placeholder="请输入微信姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="name">
          <el-input v-model="temp.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="上传微信头像" prop="name"  v-if = 'dialogStatus=="create"||temp.is_system==1'>
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :action="lujing"
            :on-success="upwx_image"

          >
            <img v-if="temp.wxhead_image" :src="temp.wxhead_image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="轮播图" prop="name">
          <el-upload
            :action="lujing"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-success="handleAvatarSuccess"
            multiple
             accept=".jpg, .jpeg,.png,.gif"
            :file-list="fileList"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="视频(没有留空)" prop="name" v-if=''>
          <el-upload
           v-if='dialogFormVisible'
            class="upload-demo"
            :action="lujing2"
            :on-success="yinpin_c"
            :on-remove="yinpin_s"
            accept=".mp3, .mp4"
            :file-list="yin_file_list"
            :limit="1"
            >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>

        </el-form-item>
        <el-form-item label="简介" prop="name">
          <el-input v-model="temp.content" placeholder="请输入简介" />
        </el-form-item>

        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog title="加票" :visible.sync="dialogFormVisible2">
      <el-form ref="dataForm" :model="temp" label-position="top" label-width="70px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="类型" prop="name">
          <el-select
          v-model="listQuery.type"
          >
            <el-option :key="0" label="加" :value="0" />
            <el-option :key="1" label="减少" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="票数" prop="name">
          <el-input-number v-model="jiapiao.number" :min="1" />
        </el-form-item>

        <div class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog title="打赏" :visible.sync="dialogFormVisible3">
      <el-form ref="dataForm" :model="temp" label-position="top" label-width="70px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="礼物" prop="name">
          <el-select
          v-model="song.id"
          >
            <el-option
            v-for="item in gift"
            :key="item.id"
            :label="item.name+'-'+item.jiaz+'票'"
            :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="name">
          <el-input-number v-model="song.number" :min="1" />
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible3 = false">
            取消
          </el-button>
          <el-button type="primary" @click="dashang()">
            确认
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  // 引入api
  import api from '@/api/vote/order_list.js'

  // 引入分页
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  export default {
    components: { Pagination },
    data() {
      return {
        jiapiao:{
          number:0
        },
        song:{
          id:null,
          number:1
        },
        gift:[],
        // 分页
        total: 0,
        pagesizes: [10, 30, 60, 100,1000,10000],
        // 列表数据
        tableData: [],
        // 权限列表
        roleData: null,
        // 权限列表筛选用
        roleData_: [
          {
            id: 0,
            name: '全部权限'
          }
        ],
        // 根据权限筛选
        rolemodel: 0,
        // 提交数据
        temp: {

        },
        yin_file_list:null,
        dialogFormVisible2:false,
        dialogImageUrl: '',
        //lujing: 'https://vote.sdxckj.work/common/wx/allupdate',
        lujing: JSON.parse(localStorage.getItem('Config'))['image_update']['value'],
        lujing2: JSON.parse(localStorage.getItem('Config'))['video_update']['value'],
        // 密码
        password: '',
        // 判定加载
        loading: false,
        dialogVisible: false,
        // 判定where
        listQuery: {
          type:null,
          page: 1,
          limit: 10,
          title: null,
          sort: 'asc',
          activity_id:null,
          fenzu_id:null,
          register_id:null
        },
        // 判定显示
        dialogFormVisible: false,
        dialogFormVisible3:false,
        // 判定修改or添加
        dialogStatus: '',
        // 判定修改id
        up_id: 0,
        // 列表匹配数据群
        textMap: {
          update: '修改',
          create: '添加'
        },
        affix2: [
          {
            value: 0,
            label: '保留'
          },
          {
            value: 1,
            label: '不保留'
          }
        ],
        fileList:'',
        show: [
          {
            value: 0,
            label: '展示'
          },
          {
            value: 1,
            label: '不展示'
          }
        ],
        sortOptions: [
          { label: 'ID 升序', key: 'asc' },
          { label: 'ID 降序', key: 'desc' }
        ],
        multipleSelection:[],
        fenzu:null,
        fenzu2:null,
        activity:null,
        userinfo:JSON.parse(localStorage.getItem("userInfo")),
        register_list:null
      }
    },
    // 进入页面加载数据
    created() {
      var activity_id = this.$route.query.id;
      this.listQuery.activity_id = activity_id;
      if(!activity_id){
         this.$router.push('/vote/activity');
      }
      this.list()
    },
    methods: {
      yinpin_c(response, file) {

        this.temp.video_url = response.data
        console.log(this.dialogImageUrl);
        this.$forceUpdate()
      },
      yinpin_s(file, fileList) {

        this.temp.video_url = null
        console.log(this.temp.banner);
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        console.log(this.multipleSelection)
      },
      formatJson(filterVal) {
        var tableData_ex = JSON.parse(JSON.stringify(this.tableData));
        return tableData_ex.map(v => filterVal.map(j => {
          //遍历修改数据
          if (j === 'birth_time') {

            return this.timestampToTime(v[j])
          }else if(j==='zdy_arr'){
            var string = null;
            var obj = v[j]
            for (let key in obj) {

              if(!string){
                string = key+':'+obj[key]
              }else{
                string+= '、'+key+':'+obj[key]
              }
            }
            if(!string){
              string = '';
            }

            v[j] =string
            return v[j]
          } else {
            return v[j]
          }


        }))
      },
      //时间戳转换
      timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
        var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
        return Y + M + D + h + m + s;
      },
      //导出
      handleDownload() {
        // this.downloadLoading = true
        // import('@/vendor/Export2Excel').then(excel => {
        //   const tHeader = ['ID', '编号', '姓名', '手机号', '票数', '礼物金额', '浏览量', '参赛宣言','额外字段','分组']
        //   const filterVal = ['id', 'code', 'name', 'phone', 'number', 'allncome', 'see_number', 'content','zdy_arr','fenzu_name']

        //   console.log(this.activity)
        //   const data = this.formatJson(filterVal)
        //   excel.export_json_to_excel({
        //     header: tHeader,
        //     data,
        //     filename:this.activity.title
        //   })
        //   this.downloadLoading = false
        // })

        this.loading = true
        var than = this
        api.order_list_exc({
          role_id: this.rolemodel,
          listQuery: this.listQuery
        }).then(res => {
          console.log('activity',res)
          //window.open(res);

          window.open(res.data.url,'_blank')
          than.loading = false
          // router.addRoutes(res)
        }).catch((res) => {
          console.log(res)
          than.loading = false
        })
      },
      up_banner(fileList){
        var arr = [];
        for(var i=0;i<fileList.length;i++){
          arr[arr.length] = fileList[i].url
        }
        this.temp.banner = arr
        console.log(this.temp.banner);
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
        this.up_banner(fileList)

      },
      upwx_image(response, file) {

        this.temp.wxhead_image = response.data

        console.log(this.temp.banner);
        this.$forceUpdate()
      },
      handleAvatarSuccess(response, file) {

        if(!this.temp.banner){
          this.temp.banner = [response.data]
        }else{
          this.temp.banner = [...this.temp.banner,response.data]
        }

        console.log(this.temp.banner);
        this.$forceUpdate()
      },
      handlePictureCardPreview(file) {

        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleAvatarSuccess2(response, file) {


        this.temp.video_url = response.data
        console.log(this.temp.banner);
        this.$forceUpdate()
      },
      go_datalist(id){
        this.$router.push({path:'/vote/datalist',query:{id:id}});
      },
      go_pinglun(id){
         this.$router.push({path:'/vote/toupiaolist',query:{id:id}});
      },
      go_info(id){

         this.$router.push({path:'/vote/gift_info',query:{id:id}});
      },
      // 冻结
      handleType(row, index, id, type) {
        var than = this
        var arr = ['解除冻结账号可正常登陆, 是否继续?', '冻结账号将无法正常登陆, 是否继续?']
        this.$confirm(arr[type], '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          api.frost({
            id: id,
            type: type
          }).then(() => {
            this.loading = false
            // this.list.unshift(this.temp)
            than.list()
            than.dialogFormVisible = false
            arr = ['启用成功', '禁用成功']
            than.$notify({
              title: '提示',
              message: arr[type],
              type: 'success',
              duration: 2000
            })
          })
        }).catch(() => {
          than.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      // 删除
      handleDelete(id,type=0) {
        if(id==0){
          id = ''
          for(var i=0;i<this.multipleSelection.length;i++){
              if(id==''){
                id = this.multipleSelection[i]['id']
              }else{
                id+= ','+this.multipleSelection[i]['id']
              }
          }
        }
        var than = this
        this.$confirm('该操作将永久删除该账号, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          api.del({
            type:type,
            id: id
          }).then(() => {
            this.loading = false
            // this.list.unshift(this.temp)
            than.list()
            than.dialogFormVisible = false
            than.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        }).catch(() => {
          than.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      //打赏
      dashang() {
        this.loading = true
        var than = this
        api.dashang({
          number:this.song.number,
          gift_id:this.song.id,
          register_id: this.up_id,
        }).then(res => {
          this.list()
          this.dialogFormVisible = false
          this.dialogFormVisible3 = false
          // router.addRoutes(res)
        }).catch((res) => {
          console.log('22222')
          than.loading = false
        })
      },
      // 修改
      updateData() {
        this.loading = true
        var than = this
        console.log(this.jiapiao.number)
        this.temp.password = this.password
        if(this.jiapiao.number){
          this.temp.number = this.jiapiao.number
        }
        api.update({

          id: this.up_id,
          temp: {
            ...this.temp,
            activity_id:this.listQuery.activity_id,
            type:this.listQuery.type
          }
        }).then(res => {
          this.list()
          this.dialogFormVisible = false
          this.dialogFormVisible2 = false
          // router.addRoutes(res)
        }).catch((res) => {
          console.log('22222')
          than.loading = false
        })
      },
      // 添加
      createData() {
        this.loading = true
        var than = this
        console.log(this.temp)
        this.temp.password = this.password
        api.save({

          temp: {
            ...this.temp,
            activity_id:this.listQuery.activity_id
          }
        }).then(res => {
          this.list()
          this.dialogFormVisible = false
          // router.addRoutes(res)
        }).catch((res) => {
          console.log('22222')
          than.loading = false
        })
      },
      // 还原提交数据
      resetTemp() {
        this.password = ''
        for (var key in this.temp) {
          delete this.temp[key]
        }
      },
      // 添加前钩子
      handleCreate(pid) {
        this.resetTemp(pid)
        this.fileList = []
        this.dialogStatus = 'create'
        this.listQuery.type = null
        this.dialogFormVisible = true
        this.yin_file_list = null
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 修改前钩子
      handleUpdate(row) {
        this.up_id = row.id
        this.password = ''
        this.temp = Object.assign({}, row) // copy obj
        console.log(this.temp)
        this.listQuery.type = null
        this.fileList = []
        for(var i=0;i<this.temp.banner.length;i++){
          this.fileList[this.fileList.length] = {
            name:i,
            url:this.temp.banner[i]
          }

        }
        this.song = {
          id:null,
          number:1
        }
        if(this.temp.video_url){
          this.yin_file_list = [{

              name:this.temp.video_url,
              url:this.temp.video_url

          }]
        }else{
          this.yin_file_list = []
        }

        this.jiapiao.number = null
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      //打赏钩子
      dashanggouzi(row) {
        this.up_id = row.id
        this.password = ''
        this.temp = Object.assign({}, row) // copy obj
        console.log(this.temp)

        this.fileList = []
        for(var i=0;i<this.temp.banner.length;i++){
          this.fileList[this.fileList.length] = {
            name:i,
            url:this.temp.banner[i]
          }

        }

        this.dialogStatus = 'update'
        this.dialogFormVisible3 = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 加票钩子
      jiapiaogouzi(row) {
        this.up_id = row.id
        this.password = ''
        this.temp = Object.assign({}, row) // copy obj
        console.log(this.temp)
        this.jiapiao.number = 0
        this.fileList = []
        for(var i=0;i<this.temp.banner.length;i++){
          this.fileList[this.fileList.length] = {
            name:i,
            url:this.temp.banner[i]
          }

        }

        this.dialogStatus = 'update'
        this.dialogFormVisible2 = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 获取列表
      list(title) {
        this.loading = true
        var than = this
        api.list({

          role_id: this.rolemodel,
          listQuery: this.listQuery
        }).then(res => {
          than.tableData = res.data.list
          than.total = res.data.count
          than.register_list = [{
              name:'全部',
              id:null
            },...res.data.register]



          than.activity = res.data.activity
          console.log('activity',res.data)
          than.gift = res.data.gift
          than.loading = false
          // router.addRoutes(res)
        }).catch((res) => {
          console.log('22222')
          than.loading = false
        })
      },
      // 排序
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = 'asc'
        } else {
          this.listQuery.sort = 'desc'
        }
        this.handleFilter()
      },
      // 还原数据
      handleFilter() {
        this.listQuery.page = 1
        this.list()
      }
    }
  }
</script>
